package org.skyui.views;

import java.util.Collection;
import java.util.List;

import org.skyui.beanmanagers.BeanRelationManager;
import org.skyui.beanmanagers.BeanSetManager;
import org.skyui.beans.AbstractBean;
import org.skyui.config.BeansTableViewConfig;
import org.skyui.controllers.ExistingBeansTableController;

import com.vaadin.data.util.BeanItem;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.ui.Component;

public class ExistingBeansTableView extends AbstractBeansTableView implements
		ItemClickEvent.ItemClickListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8978019425307376427L;

	public ExistingBeansTableView(String name, String explanation,
			boolean showTableCaption, BeanSetManager beanManager) {
		super(name, explanation, showTableCaption, beanManager, true);
		this.setController(new ExistingBeansTableController(beanManager, this));
	}

	
	public void itemClick(ItemClickEvent event) {

		BeanItem<? extends AbstractBean> item = (BeanItem<? extends AbstractBean>) event
				.getItem();

		removeSelectedComponent();

		if (this.getTabSheet() == null) {
			this.setTabSheet(new NavigationTabSheet());
			this.getLayout().addComponent(this.getTabSheet());
		}

		AbstractBeanView st = new ExistingBeanView("", "", item.getBean(), this
				.getApplication());
		st.setParentTab(this);
		st.setCaption(BeansTableViewConfig
				.getSelectedItemCaption((BeanSetManager) this.getBeanManager()));
		this.getSelectedItemTabs().add(st);
		Collection<BeanRelationManager> mgrs = item.getBean()
				.getOwnedBeansManagers();

		if (mgrs != null) {
			for (BeanRelationManager mgr : mgrs) {
				if (!mgr.isVisible())
					continue;
				BeansRelationTableView itemTable = new BeansRelationTableView(
						"", "", mgr);
				this.getSelectedItemTabs().add(itemTable);
			}
		}

		List<Component> selectedItemTabs = this.getSelectedItemTabs();
		for (Component comp : selectedItemTabs) {
			this.getTabSheet().addComponent((Component) comp);
		}
	}
}